package operation.modules.operation.service.impl;

import com.alibaba.fastjson.JSONObject;
import freemarker.template.TemplateException;
import operation.freeMarker.util.FreemarkerUtil;
import operation.modules.operation.dto.TranslateDTO;
import operation.modules.operation.dto.TranslateResultDTO;
import operation.modules.operation.service.TranslateService;
import operation.translate.dome.TransApi;
import operation.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

@Service("translateService")
public class TranslateServiceImpl implements TranslateService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    // 多语言处理模板地址
    private final String basePath = "D:\\workspace\\abandon-me\\";
    private final String ftlPathTranslate = "server\\src\\main\\java\\operation\\translate\\multilingual\\";

    /**
     * 生成安卓代码实现方法
     * @param params
     * @return
     */
    public TranslateDTO translate(Map<String, Object> params) {
        String APP_ID = (String) params.get("appId");
        String SECURITY_KEY = (String) params.get("securityKey");
        String translateType = (String) params.get("translateType");
        String translateType2 = (String) params.get("translateType2");
        String langCN = (String) params.get("langCN");
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        langCN = StringUtil.replaceSpecialStr(langCN);

        if(translateType.equals("true")) {
            if(String.valueOf(langCN.charAt(langCN.length()-1)).equals(",") || String.valueOf(langCN.charAt(langCN.length()-1)).equals(",\n")) {
                langCN.substring(0, langCN.length()-1);
            }
            // 处理web
            String[] list1;
            if (translateType2.equals("true")) {
                // 处理android
                // <string name="api_code_msg_app_server_error_inventory_amend_complete_not_amend">该单据状态为库存修正完成，不可修正</string>
                list1 = langCN.split("</string>");
            } else {
                list1 = langCN.split(",");
            }

            Map<String, Object> map = new HashMap<>();
            for(int i = 0; i < list1.length; i++) {
                TranslateDTO translateDTO = new TranslateDTO();
                String strCN;
                if (translateType2.equals("true")) {
                    // android
                    strCN = list1[i].substring(list1[i].indexOf(">") + 1);
                } else {
                    // web
                    strCN = list1[i].substring(list1[i].indexOf("'") + 1, list1[i].lastIndexOf("'"));
                }


                String strEN = api.getTransResult(strCN,"auto", "en");
                String strTW = api.getTransResult(strCN,"auto", "cht");
                String strJA = api.getTransResult(strCN,"auto", "jp");
                TranslateResultDTO enE = (TranslateResultDTO) JSONObject.toJavaObject(JSONObject.parseObject(strEN), TranslateResultDTO.class);
                TranslateResultDTO enT = (TranslateResultDTO) JSONObject.toJavaObject(JSONObject.parseObject(strTW), TranslateResultDTO.class);
                TranslateResultDTO enJ = (TranslateResultDTO) JSONObject.toJavaObject(JSONObject.parseObject(strJA), TranslateResultDTO.class);
                if (translateType2.equals("true")) {
                    translateDTO.setName(list1[i].split(">")[0].split("=")[1]); // android
                } else {
                     translateDTO.setName(list1[i].split(":")[0]); // web
                }
                translateDTO.setCn(strCN);
                translateDTO.setEn(enE.getTransResult().get(0).getDst());
                translateDTO.setTw(enT.getTransResult().get(0).getDst());
                translateDTO.setJa(enJ.getTransResult().get(0).getDst());

                map.put(String.valueOf(i),translateDTO);
                if(i == 0) {
                    System.out.println("凡哥为你持续翻译.....\n");
                }
                System.out.println("第" + i + "个:" +
                        "\t中文:" + translateDTO.getCn() +
                        "\t英文:" + translateDTO.getEn() +
                        "\t繁体:" + translateDTO.getTw() +
                        "\t日文:" + translateDTO.getJa() + "\n");
                if(i == list1.length - 1) {
                    System.out.println("翻译完成,为您生成多语言代码中.....");
                }
            }
            // 处理MAP
            List<TranslateDTO> list = new ArrayList<>();
            for(int j = 0; j < map.size(); j++) {
                list.add((TranslateDTO) map.get(String.valueOf(j)));
            }

            Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int date = c.get(Calendar.DATE);
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
            int second = c.get(Calendar.SECOND);
            String time = year + "年" + month + "月" + date + "日--" + hour + "时" + minute + "分" + second + "秒";
            Map<String, Object> mapFtl = new HashMap<>();
            mapFtl.put("list", list);
            mapFtl.put("time", time);
            try {
                TranslateAutoWrite(mapFtl, translateType2);
            } catch (IOException e) {
                System.out.println("IOException异常,生成代码失败!");
                e.printStackTrace();
            } catch (TemplateException e) {
                System.out.println("模板异常,生成代码失败!");
                e.printStackTrace();
            }
            // 打开txt
            File f=new File(basePath + ftlPathTranslate + "多语言代码.txt");
            System.out.println("文件是否存在:" + f.exists());
            try {
                Desktop.getDesktop().open(f);
                System.out.println("打开文件成功:" + basePath + ftlPathTranslate + "多语言代码.txt");
            } catch (IOException e) {
                System.out.println("打开文件失败");
                e.printStackTrace();
            }
            // 拼返回数据
            String res = "详见[多语言代码.txt]文件";
            TranslateDTO returnDTO = new TranslateDTO();
            returnDTO.setJa(res);
            returnDTO.setEn(res);
            returnDTO.setTw(res);
            return returnDTO;

        } else {
            TranslateDTO translateDTO = new TranslateDTO();
            String strEN = api.getTransResult(langCN,"auto", "en");
            String strTW = api.getTransResult(langCN,"auto", "cht");
            String strJA = api.getTransResult(langCN,"auto", "jp");
            TranslateResultDTO enE = (TranslateResultDTO) JSONObject.toJavaObject(JSONObject.parseObject(strEN), TranslateResultDTO.class);
            TranslateResultDTO enT = (TranslateResultDTO) JSONObject.toJavaObject(JSONObject.parseObject(strTW), TranslateResultDTO.class);
            TranslateResultDTO enJ = (TranslateResultDTO) JSONObject.toJavaObject(JSONObject.parseObject(strJA), TranslateResultDTO.class);
            translateDTO.setEn(enE.getTransResult().get(0).getDst());
            translateDTO.setTw(enT.getTransResult().get(0).getDst());
            translateDTO.setJa(enJ.getTransResult().get(0).getDst());
            System.out.println("中文:" + langCN +
                    "\n英文:" + enE.getTransResult().get(0).getDst() +
                    "\n繁体:" + enT.getTransResult().get(0).getDst() +
                    "\n日文:" + enJ.getTransResult().get(0).getDst());
            return translateDTO;
        }
    }

    public void openTxt() {
        File f=new File(basePath + ftlPathTranslate + "多语言代码.txt");
        System.out.println("文件是否存在:" + f.exists());
        try {
            Desktop.getDesktop().open(f);
            System.out.println("打开文件成功:" + basePath + ftlPathTranslate + "多语言代码.txt");
        } catch (IOException e) {
            System.out.println("打开文件失败");
            e.printStackTrace();
        }
    }

    // 输出文件
    public void TranslateAutoWrite(Map<String, Object> map, String type) throws IOException, TemplateException {
        if (type.equals("true")) {
            FreemarkerUtil.initConfig(3, "mulA.ftl");
        } else {
            FreemarkerUtil.initConfig(3, "mul.ftl");
        }
        String allPath = basePath + ftlPathTranslate + "多语言代码.txt";
        // 生成多语言代码
        FreemarkerUtil.generator(allPath, map);
        System.out.println("文件路径:" + allPath + "\n");
    }

}
